package com.thank.concurrency.samples.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 演示Semaphore 设置超时时间, 超时的就丢弃
 */
@Slf4j
public class SemaphoreExample4 {

    private final static int threadCount = 20;

    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(3); // 注意这里的permits

        for (int i = 0; i < threadCount; i++) {
            final int threadNum = i;
            exec.execute(() -> {
                try {
                    // 设置超时时间3秒
                    if (semaphore.tryAcquire(3000, TimeUnit.MILLISECONDS)) { // 尝试获取一个许可
                        test(threadNum); // 只会输出大概3秒, 3*3大约9个
                        semaphore.release();
                    }
                } catch (Exception e) {
                    log.info("exception:", e);
                }
            });
        }

        exec.shutdown();
    }

    private static void test(int threadNum) throws Exception {
        Thread.sleep(1000);
        log.info("{}", threadNum);
    }
}
